//
//  EOCSoundPlayer.m
//  Test
//
//  Created by 杨德龙 on 2017/6/15.
//  Copyright © 2017年 HipalSports. All rights reserved.
//

#import "EOCSoundPlayer.h"
#import <AudioToolbox/AudioToolbox.h>    // 引进 播放音频的 toolBox

EOCSoundPlayer *_soundPlayer;

// 完成的comletion 函数
void completion(SystemSoundID ssID,void *clientData){
    
    // AudioServicesRemoveSystemSoundCompletion (ssID);
    // 报错
    /*
     !!!!!  按照书上的敲法这样 敲失败
     EOCSoundPlayer *player=(__bridge EOCSoundPlayer *)clientData;  // 实际这个clientData  并不是 EOCSoundPlayer
     NSLog(@"client data is %@",player);
     //    EOCSoundPlayer *player=self;  CAlayer 类型
     if ([player.delegate respondsToSelector:@selector(soundPlayerDidFinish:)]) {
     [player.delegate soundPlayerDidFinish:player];
     }
     */
    
    //  !!  下面是 笔者修改 好的 
    if (_soundPlayer&&[_soundPlayer.delegate respondsToSelector:@selector(soundPlayerDidFinish:)]) {
        [_soundPlayer.delegate soundPlayerDidFinish:_soundPlayer];
    }
}

@implementation EOCSoundPlayer
{
    SystemSoundID _systemSoundID;
    
}

- (instancetype)initWithUrl:(NSURL *)url
{
    if (self=[super init]) {
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &_systemSoundID);
    }
    return self;
}


/**
 记住要 dispose
 */
- (void)dealloc
{
    AudioServicesDisposeSystemSoundID(_systemSoundID);
}

#pragma mark ---- Public Method
- (void)playSound
{
    _soundPlayer=self;
    
    AudioServicesAddSystemSoundCompletion(
                                          _systemSoundID,
                                          NULL,
                                          NULL,
                                          completion,
                                          (__bridge void*)self),
     AudioServicesPlaySystemSound(_systemSoundID);
                                          
    
}



@end
